package com.itfreer.userProof;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.bpm.api.IRestProofReadUser;
import com.itfreer.bpm.power.para.UserInfo;
import com.itfreer.jwt.JwtTicket;
import com.itfreer.jwt.JwtTicketFactory;
import com.itfreer.power.entity.user.VUserInfoEntity;
@Component
public class UserProof implements IRestProofReadUser {
	private final static String s_user = "user";
	@Autowired
	private JwtTicketFactory jwtTicketFactory;

	@Override
	public void ProofReadUser(HttpServletRequest request, String data, UserInfo user) {
		
		String jwt = request.getHeader("jwt");
		if (jwt == null || jwt.trim().equals("")) {
			System.out.println("获取登录用户失败");
		}

		JwtTicket ticket = jwtTicketFactory.getTicket(request);
		VUserInfoEntity userEntity = ticket != null ? (VUserInfoEntity) ticket.getAttribute().get(s_user) : null;

		if (user == null) {
			user = new UserInfo();
		}

		if (userEntity != null) {
			// 是否是超级管理员
			Boolean isSa = userEntity.getIsSuperAdmin();

			if (null == isSa || isSa == false) {// 不是超级管理员
				if (null == userEntity.getUserid() || "".equals(userEntity.getUserid())) {
					System.out.println("***************************获取用户id失败******************************************");
					throw new RuntimeException("获取用户id失败");
				}

				if (null == userEntity.getOrganizationId() || "".equals(userEntity.getOrganizationId())) {
					System.out
							.println("***************************获取用户组织机构失败******************************************");
					throw new RuntimeException("获取用户组织机构失败");
				}

				user.setSuperAdmin(false);
			} else {
				user.setSuperAdmin(isSa);
			}

			user.setUserId(userEntity.getUserid());
			user.setUserOrgCode(userEntity.getOrganizationId());
			user.setUserAccount(userEntity.getAccounts());
			user.setUserName(userEntity.getUserName());
			user.setUserOrgName(userEntity.getOrganizationName());
			user.setUserDepCode(userEntity.getDepartmentId());
			user.setUserDepName(userEntity.getDepartmentName());

		} else {
			System.out.println("***************************获取用户失败******************************************");
			throw new RuntimeException("获取用户失败");
		}
	}
}
